package socket;

import SPI.javaspi.GirlSayHello;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.Socket;
import java.time.LocalDateTime;
import java.util.Iterator;
import java.util.Map;
import java.util.ServiceLoader;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author MaoLin Wang
 * @description
 * @date 2020/9/30 9:00 上午
 */
public class ServerRunnable implements Runnable {
    private final Socket socket;

    public ServerRunnable(Socket socket) {
        this.socket = socket;
    }

    private static Map<String,Object> services=new ConcurrentHashMap<>();
    static {
        try {
            services.put("hello",GirlSayHello.class.newInstance());
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        try {
            Thread.sleep(1000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName());
        try (ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
             ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream())) {
            RpcRequest rpcRequest = (RpcRequest) ois.readObject();
            System.out.println("receive request from client ,request is " + rpcRequest.toString());
            Object o = services.get(rpcRequest.getInterfaceName());
            Method declaredMethod = o.getClass().getDeclaredMethod(rpcRequest.getMethodName());
            Object result = declaredMethod.invoke(o, null);

            System.out.println("response to server:" + result);
            oos.writeObject(result);
            oos.flush();
        } catch (IOException | ClassNotFoundException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
        }
    }
}
